import os, sys, stat
import re
import subprocess
import shutil
import time
from os.path import join as path_cat

def make_symbolic_link_file(link_path, target_path):
    try:
        try:
            os.readlink(link_path)  # check if it is a symbolic(junction) link, or will except
            os.unlink(link_path)    # remove the symbolic link
        except OSError as e:        # it is not exist or not a symbolic link, remove it
            if os.path.isfile(link_path):
                os.remove(link_path)
            elif os.path.exists(link_path):
                shutil.rmtree(link_path)
        subprocess.run(['mklink', link_path, target_path], check=True, shell=True)
    except subprocess.CalledProcessError as e:
        print(f"***@Err@*** Creating symbolic link: {e}")

def make_symbolic_link_dir(link_path, target_path):
    try:
        try:
            os.readlink(link_path)  # check if it is a symbolic(junction) link, or will except
            os.unlink(link_path)    # remove the symbolic link
        except OSError as e:        # it is not exist or not a symbolic link, remove it
            if os.path.isfile(link_path):
                os.remove(link_path)
            elif os.path.exists(link_path):
                shutil.rmtree(link_path)
        if os.path.isfile(target_path):
            shutil.copy(target_path, link_path)
        else:
            subprocess.run(['mklink', '/D', link_path, target_path], check=True, shell=True)
    except subprocess.CalledProcessError as e:
        print(f"***@Err@*** Creating symbolic link: {e}")

def make_symbolic_link_tree(link_path, target_path, protect_dir:list):
    for entry in os.scandir(target_path):
        if entry.name in protect_dir: # protect dir
            continue
        link_dir = path_cat(link_path, entry.name)
        target_dir = path_cat(target_path, entry.name)
        if os.path.isfile(link_dir): # exist file 
            continue
        make_symbolic_link_dir(link_dir, target_dir)


def list_and_select_directory(base_path="."):
    """
    列出指定路径下的所有子目录，允许用户通过输入序号进行选择
    
    Args:
        base_path: 基础路径，默认为当前目录
    
    Returns:
        selected_path: 用户选择的目录路径，如果用户未选择或输入错误则返回None
    """
    try:
        # 获取所有子目录
        subdirs = [d for d in os.listdir(base_path) 
                  if d != r"@doc" and d != r"_simu" and d != r"sdk" and os.path.isdir(os.path.join(base_path, d))]
        
        # 如果没有子目录
        if not subdirs:
            print("当前路径下没有子目录")
            return None
            
        # 显示子目录列表
        print("\n当前路径下的子目录:")
        for i, subdir in enumerate(subdirs):
            print(f"{i+1}. {subdir}")
            
        # 用户选择
        while True:
            try:
                choice = input(f"\n请选择目录序号 (1-{len(subdirs)})，或按回车使用默认值: ")
                if not choice:
                    return None  # 用户未选择
                choice_index = int(choice) - 1
                if 0 <= choice_index < len(subdirs):
                    selected_path = os.path.join(base_path, subdirs[choice_index])
                    print(f"已选择目录: {subdirs[choice_index]}")
                    return selected_path
                else:
                    print(f"请输入有效序号 (1-{len(subdirs)})")
            except ValueError:
                print("请输入有效的数字")
                
    except Exception as e:
        print(f"获取目录列表时出错: {e}")
        return None
    

def main():
    print("Akm 6g platform - CH584 - 800K, Deploy development environment...... ")

    # prj_name = input("请输入项目名称 (默认为1041_584_800K): ")
    cur_path = os.getcwd()
    # 列出当前路径下的子目录，用户可以列表序号选择目录
    prj_name = list_and_select_directory(path_cat(cur_path, r".."))

    if not prj_name:
        print("**********@Err@********** 未选择项目, 请检查项目目录结构是否正确")
        # prj_name = "1041_584_800K"
        return

    m0_dir = path_cat(cur_path, r"..", prj_name, "m0")
    cat1_dir = path_cat(cur_path, r"..", prj_name, "cat1")
    # 侦测cat项目类型, 尝试hs2131/800k/800g
    cat1_app_path = path_cat(cat1_dir, r"application\cat1\custom_app\zq_app") # hs2131
    if (not os.path.exists(cat1_app_path)) or (not os.path.isdir(cat1_app_path)):
        cat1_app_path = path_cat(cat1_dir, r"ql-application\threadx\interface\zq_app") # 800k
        if (not os.path.exists(cat1_app_path)) or (not os.path.isdir(cat1_app_path)):
            cat1_app_path = path_cat(cat1_dir, r"components\ql-application\zq_app") # 800g
            if (not os.path.exists(cat1_app_path)) or (not os.path.isdir(cat1_app_path)):
                print("**********@Err@********** 不能识别项目的cat1部分, 请检查项目目录结构是否正确")
                return
    simu_dir = path_cat(cur_path, "simu")

    # 1. simu
    make_symbolic_link_dir(path_cat(cur_path, r"m0\src"), path_cat(m0_dir, "src"))
    make_symbolic_link_dir(path_cat(cur_path, r"cat1\zq_app"), path_cat(cat1_dir, cat1_app_path))

    # 删除旧的simu运行文件
    dirB = path_cat(cur_path, r"zy_simu\release\app")
    if os.path.exists(dirB):
        shutil.rmtree(path_cat(cur_path, dirB))

# =============================================================================================================================
if __name__ == '__main__':
    main()
    os.system('pause')
